const { createOrUpdate, findCart, updateCart, removeCart, selectAllCart, unselectAllCart } = require('../service/cart.service')
const { cartFormatError } = require('../consisitant/err.type')
class CartController {
    async add(ctx) {
        // const user_id = ctx.state.user.user_id
        const user_id = ctx.request.body.user_id
        const goods_id = ctx.request.body.goods_id
        const res = await createOrUpdate(user_id, goods_id)
        ctx.body = {
            code: 0,
            message: "商品添加成功",
            result: res
        }
    }
    async findAll(ctx) {
        const { pageNum = 1, pageSize = 10 } = ctx.request.query
        const res = await findCart(pageNum, pageSize)
        ctx.body = {
            code: 0,
            message: '获取购物车列表成功',
            result: res
        }
    }
    async update(ctx) {
        const { id } = ctx.request.params
        const { number, selected } = ctx.request.body
        if (number === undefined && selected === undefined) {
            cartFormatError.message = "number和selected不能同时为空"
            return ctx.app.emit('error', cartFormatError, ctx)
        }
        const res = await updateCart({ id, number, selected })
        ctx.body = {
            code: 0,
            message: '更新购物车成功',
            result: res
        }
    }
    async remove(ctx) {
        const { ids } = ctx.request.body
        const res = await removeCart(ids)
        ctx.body = {
            code: 0,
            message: "删除购物车成功",
            resukt: res
        }
    }
    async selecAll(ctx) {
        const user_id = ctx.state.user.id
        const res = await selectAllCart(user_id)
        ctx.body = {
            code: 0,
            message: "购物车全部选中",
            result: res
        }
    }
    async unselectAll(ctx) {
        const user_id = ctx.state.user.id
        const res = await unselectAllCart(user_id)
        ctx.body = {
            code: 0,
            message: "购物车全不选中",
            result: res
        }
    }
}

module.exports = new CartController()